package dao;

import application.exceptions.ItemNotFoundException;
import mappings.Country;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import utils.HibernateUtil;

@SuppressWarnings("JpaQlInspection")
public class CountryDao
{
    private static SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    public Country addCountry(String name)
    {
        Country country = new Country();
        country.setName(name);

        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        session.save(country);

        tx.commit();
        session.close();

        return country;
    }

    public Country editCountry(Integer id, Country country) throws ItemNotFoundException
    {
        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        Country countryToEdit = (Country) session.get(Country.class, id);

        if(countryToEdit == null)
        {
            tx.rollback();
            session.close();
            throw new ItemNotFoundException();
        }

        countryToEdit.setName(country.getName());
        session.update(countryToEdit);
        tx.commit();
        session.close();

        return countryToEdit;
    }

    public void deleteCountry(Integer id) throws ItemNotFoundException
    {
        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        int affectedRows = session.createQuery("delete Country where id = :id")
                .setParameter("id", id)
                .executeUpdate();

        if(affectedRows == 0)
        {
            tx.rollback();
            session.close();
            throw new ItemNotFoundException();
        }

        tx.commit();
        session.close();
    }
}
